<template>
  <view class="order-list-container">
    <u-navbar :title="title" :is-back="true" title-color="black" :border-bottom="false" :custom-back="customBack"
              :background="background"/>
    <scroll-view scroll-x class="status-tabs" enable-flex>
      <view
          v-for="(tab, index) in tabs"
          :key="index"
          :class="['tab-item row', { active: activeTab === tab.status }]"
          @click="changeTab(tab.status)"
      >
        <text class="tab-label">{{ tab.label }}</text>
        <text :class="[ { tablineactive: activeTab === tab.status }]"></text>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <scroll-view
        scroll-y
        class="orders-scroll"
        @scroll="handleScroll"
        enable-flex
        scroll-with-animation
        enable-passive
    >
      <view v-if="filteredOrders.length === 0" class="no-orders">暂无订单</view>
      <view
          v-for="(order, index) in filteredOrders"
          :key="index"
          class="order-card"

      >

        <view class="order-details">

          <view class="order-info column">
            <view class="order-item row">
              <view class="order-label">订单编号:</view>
              <view class="flex-1 row-between">
                <text class="order-value">{{ order?.order_number }}</text>
                <view class="copy-icon " @click="copyText(order.order_number)">复制</view>
              </view>
            </view>
            <view class="order-item">
              <text class="order-label">联系方式:</text>
              <text>{{ order.contact_number }}</text>
            </view>
            <!--            <view class="order-item">-->
            <!--              <text class="order-label">回收类型:</text>-->
            <!--              <text>{{ order.recycle_type === '1' ? '衣服' : '鞋帽' }}</text>-->
            <!--            </view>-->
            <view class="order-item">
              <text class="order-label">预估重量:</text>
              <text>{{ order.estimated_weight }}</text>
            </view>
            <view class="order-item" v-if="order.order_status === '2'">
              <text class="order-label">实际重量:</text>
              <text>{{ order.actual_weight }}kg</text>
            </view>
            <view class="order-item">
              <text class="order-label">预约时间:</text>
              <text>{{ order.pickup_time }}</text>
            </view>
            <view class="order-item" v-if="order.order_status === 2">
              <text class="order-label">取件时间:</text>
              <text>{{ timeFormat(order.pick_up_time, 'yy-mm-dd hh:MM:ss') }}</text>
            </view>
            <view class="order-item">
              <text class="order-label">取件地址:</text>
              <text>{{ order.pickup_address }}</text>
            </view>

            <view class="order-item">
              <text class="order-label">订单状态:</text>
              <!--              <text>{{-->
              <!--                  order.order_status === 0 ? '等待上门' : order.order_status === 1 ? '回收中' : order.order_status === 2 ? '已完成' : order.order_status === 3 ? '已取消' : ''-->
              <!--                }}-->
              <!--              </text>-->
              <text>{{ getOrderStatusText(order.order_status, userType) }}</text>
            </view>
            <view class="order-item">
              <text class="order-label">下单时间:</text>
              <text>{{ timeFormat(order.order_time, 'yy-mm-dd hh:MM:ss') }}</text>
            </view>
          </view>
          <!--          <view class="payment">-->
          <!--            <u-button type="info" shape="circle" size="medium" class="mr20" @click="goToCustomerService">咨询客服-->
          <!--            </u-button>-->
          <!--            <u-button type="info" shape="circle" size="medium" class="mr20" @click="goToOrderDetail(order.id)">-->
          <!--              查看详情-->
          <!--            </u-button>-->
          <!--            <u-button type="primary" shape="circle" size="medium" @click="cancelOrder(order)"-->
          <!--                      v-if="order.order_status === 0">取消订单-->
          <!--            </u-button>-->
          <!--            <u-button type="primary" shape="circle" size="medium"-->
          <!--                      v-if="order.order_status === 1">回收中-->
          <!--            </u-button>-->
          <!--            <u-button type="success" shape="circle" size="medium"-->
          <!--                      v-if="order.order_status === 2">已完成-->
          <!--            </u-button>-->
          <!--            <u-button type="waring" shape="circle" size="medium" v-if="order.order_status === 3"-->
          <!--                      @click="deleteOrder(order)">-->
          <!--              删除订单-->
          <!--            </u-button>-->
          <!--          </view>-->
          <view class="payment">
            <u-button type="info" shape="circle" size="medium" class="mr20" @click="goToCustomerService">咨询客服
            </u-button>
            <u-button type="info" shape="circle" size="medium" class="mr20" @click="goToOrderDetail(order.id)">
              查看详情
            </u-button>

            <!-- 普通用户操作按钮 -->
            <template v-if="userType !== 2">
              <u-button type="primary" shape="circle" size="medium" @click="cancelOrder(order)"
                        v-if="order.order_status === 0">取消订单
              </u-button>
              <u-button type="primary" shape="circle" size="medium" v-if="order.order_status === 1">回收中</u-button>
              <u-button type="success" shape="circle" size="medium" v-if="order.order_status === 2">已完成</u-button>
              <u-button type="warning" shape="circle" size="medium" v-if="order.order_status === 3"
                        @click="deleteOrder(order)">删除订单
              </u-button>
            </template>

            <!-- 回收师傅操作按钮 -->
            <template v-else>
              <u-button type="primary" shape="circle" size="medium" v-if="order.order_status === 1"
                        @click="completeOrder(order)">完成回收
              </u-button>
              <u-button type="success" shape="circle" size="medium" v-if="order.order_status === 2">已完成回收
              </u-button>
            </template>
          </view>
        </view>
      </view>
      <!-- 在 scroll-view 底部添加 -->
      <view v-if="isLoading" class="loading-tips">加载中...</view>
      <view v-if="!hasMoreData && filteredOrders.length > 0" class="no-more"
      >没有更多订单了
      </view>
    </scroll-view>


    <tabbar/>
  </view>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {onLoad, onShow, onReady, onUnload} from '@dcloudio/uni-app'
import {apiListsOrder, apiMasterAcceptedOrders, apiCancelOrder, apiDeleteOrder, apiCompleteOrder} from "@/api/order";
import {timeFormat} from "@/utils/util";
import UButton from "@/uni_modules/vk-uview-ui/components/u-button/u-button.vue";
import {useUserStore} from '@/stores/user'

const userStore = useUserStore()
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = 10 // 每页数据量
const hasMoreData = ref(true) // 是否还有更多数据
const isLoading = ref(false) // 防止重复加载
const userType = computed(() => userStore.userInfo?.type_id)
const title = computed(() => {
  return userType.value === 2 ? '已接订单' : '我的订单'
})
const tabs = computed(() => {


  if (userType.value === 2) {
    return [
      {label: '全部', status: ''},
      {label: '回收中', status: '1'},
      {label: '已完成', status: '2'}
    ]
  } else {
    return [
      {label: '全部', status: ''},
      {label: '等待上门', status: '0'},
      {label: '回收中', status: '1'},
      {label: '已完成', status: '2'},
      {label: '已取消', status: '3'}
    ]
  }
})

const getOrderStatusText = (status, userType) => {
  if (userType === 2) {
    // 回收师傅视角
    const masterStatusMap = {
      '0': '待接单',
      '1': '回收中',
      '2': '已完成',
      '3': '已取消'
    }
    return masterStatusMap[status] || '未知状态'
  } else {
    // 普通用户视角
    const userStatusMap = {
      '0': '等待上门',
      '1': '回收中',
      '2': '已完成',
      '3': '已取消'
    }
    return userStatusMap[status] || '未知状态'
  }
}

const background = {
  position: 'fixed', // 固定定位（相对于视口）
  top: '0',         // 使用字符串并添加单位
  left: '0',
  right: '0',
  zIndex: 999       // 确保层级足够高
}
// 当前选中的 tab
const activeTab = ref('')
// 订单数据
const orders = ref([])

// 新增：刷新订单列表
const refreshOrders = async () => {
  currentPage.value = 1
  hasMoreData.value = true
  await getOrders()
}
const getOrders = async (isLoadMore = false) => {
  if (isLoading.value || !hasMoreData.value) return

  isLoading.value = true
  try {
    let data;

    if (userType === 2) {
      console.log('获取可接订单列表')
      // 回收师傅获取可接订单列表
      data = await apiMasterAcceptedOrders({
        status: activeTab.value,
        keyword: searchKeyword.value,
        page_no: isLoadMore ? currentPage.value + 1 : 1,
        page_size: pageSize
      })
    } else {
      // 普通用户获取自己的订单列表
      data = await apiListsOrder({
        status: activeTab.value,
        keyword: searchKeyword.value,
        page_no: isLoadMore ? currentPage.value + 1 : 1,
        page_size: pageSize
      })
    }

    const newOrders = data.data || []

    if (isLoadMore) {
      orders.value = [...orders.value, ...newOrders] // 追加数据
    } else {
      orders.value = newOrders // 替换数据
    }

    // 更新分页状态
    currentPage.value = isLoadMore ? currentPage.value + 1 : 1
    hasMoreData.value = newOrders.length >= pageSize // 判断是否还有数据
  } catch (error) {
    console.error('获取订单数据失败:', error)
  } finally {
    isLoading.value = false
  }
}
onMounted(async () => {
  if (!userStore.isLogin) {
    await userStore.getUser()
  }
  getOrders()
})

const goToCustomerService = () => {
  uni.navigateTo({
    url: '/pages/customer_service/customer_service'
  })
}
const filteredOrders = computed(() => {
  if (!searchKeyword.value) return orders.value
  const keyword = searchKeyword.value.toLowerCase()
  return orders.value.filter(
      (order) => order.id.includes(keyword) || order.name?.toLowerCase().includes(keyword)
  )
})
const goToOrderDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/order/order_detail?id=${id}`
  })
}

const deleteOrder = async (order) => {
  uni.showModal({
    title: "确认删除订单",
    content: `是否确认删除订单 "${order.order_number}"？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await apiDeleteOrder({
            id: order.id
          })
          uni.showToast({
            title: "删除成功",
            icon: "success"
          })
          // 刷新列表
          refreshOrders()
        } catch (error) {
          uni.showToast({
            title: "删除失败",
            icon: "error"
          })
        }
      }
    }
  })
}

const copyText = (text: string) => {
  if (!text) {
    uni.showToast({title: '订单号为空', icon: 'none'});
    return;
  }

  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({title: '复制成功', icon: 'success'});
    },
    fail: () => {
      uni.showToast({title: '复制失败，请手动复制', icon: 'none'});
    }
  });
};

const customBack = () => {
  uni.switchTab({
    url: '/pages/user/user' // 确保路径正确
  })
}
const handleScroll = (e: any) => {
  const {scrollTop, scrollHeight} = e.detail
  const systemInfo = uni.getSystemInfoSync()
  // 计算可视区域高度（窗口高度 - 导航栏高度 - 搜索框高度 - 其他固定元素高度）
  const clientHeight = systemInfo.windowHeight - 80 // 80rpx 是导航栏+搜索框估算高度

  // 增加防抖和加载锁
  if (isLoading.value) return

  // 判断是否滚动到底部（距离底部 < 10px）
  const isBottom = scrollHeight - scrollTop - clientHeight < 10
  console.log(`滚动位置: ${scrollTop}, 内容高度: ${scrollHeight}, 可视高度: ${clientHeight}`)

  console.log('滚动到底部:', isBottom)
  if (isBottom) {
    getOrders(true) // 触发加载更多
  }
}

const cancelOrder = async (order) => {
  uni.showModal({
    title: "确认取消订单",
    content: `是否确认取消订单 "${order.order_number}"？`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({title: "取消中..."});
        try {
          const success = await apiCancelOrder({id: order.id, order_status: 3});
          if (success) {
            uni.showToast({title: "订单已取消", icon: "success"});
            await refreshOrders(); // 刷新整个订单列表

          } else {
            uni.showToast({title: "取消失败", icon: "none"});
          }
        } catch (error) {
          uni.showToast({title: "取消失败，请重试", icon: "none"});
          console.error("取消订单失败:", error);
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

const completeOrder = async (order) => {
  uni.showModal({
    title: "确认完成回收",
    content: `是否确认完成回收订单 "${order.order_number}"？`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({title: "取消中..."});
        try {
          const success = await apiCompleteOrder({id: order.id, order_status: 3});
          if (success) {
            uni.showToast({title: "回收完成", icon: "success"});
            await refreshOrders(); // 刷新整个订单列表

          } else {
            uni.showToast({title: "回收订单失败", icon: "none"});
          }
        } catch (error) {
          uni.showToast({title: "回收订单失败，请重试", icon: "none"});
          console.error("回收订单失败:", error);
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

function changeTab(status: string) {
  activeTab.value = status
  refreshOrders(); // 替代 getOrders
}

onShow(() => {
  const params = uni.getStorageSync('orderPageParams');
  console.log('params:', params)
  if (params.type != undefined) {
    activeTab.value = String(params.type)
  } else {
    activeTab.value = ''
  }
  changeTab(activeTab.value)
  refreshOrders();
})

onLoad((query) => {
  console.log('query:', activeTab.value)
  const params = uni.getStorageSync('orderPageParams');
  if (params.type != undefined) {
    activeTab.value = String(params.type)
  }

  changeTab(activeTab.value)
})

</script>

<style lang="scss">
.order-list-container {
  background-image: linear-gradient(to bottom, #236af6, #ffffff); /* 添加渐变 */
  background-color: #ffffff;
  background-repeat: no-repeat;
  background-size: 100% 20%;

}


.status-tabs {
  white-space: nowrap;
  display: flex;
  overflow-x: auto;

}

.tab-item {

  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;

  &.active {
    font-size: 36rpx;
    font-weight: bold;

  }
}

.tablineactive {
  align-items: center;
  border-bottom: 4rpx solid #4a90e2;
  width: 80%;
  margin-top: 20rpx;
}


.orders-scroll {
  height: calc(100vh - 200rpx); // 增加底部预留高度
  //border: 1rpx solid red; // 添加边框辅助调试
  overflow: hidden; // 避免内容溢出
}

.no-orders {
  text-align: center;
  margin-top: 100rpx;
  color: #999;
}

.order-card {
  display: flex;
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  flex: 1;
  border-radius: 16rpx;
}

.order-image {
  width: 240rpx;
  height: 240rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
}

.order-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.order-name {
  font-size: 32rpx;
  font-weight: bold;
}

.order-date,
.order-travelers {
  font-size: 26rpx;
  color: #666;
}

.time-slot {
  display: flex;
  font-size: 24rpx;
  flex-direction: column;
  background-color: #f8f8f8;
  color: #6e7681;
  border-radius: 8rpx;
  line-height: 1.5;
  padding: 15rpx;
  margin-bottom: 15rpx;
}

.payment {
  //background-color: #fff;
  display: flex;
  justify-content: flex-end;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  color: #f6a22d;
}

.order-status {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 28rpx;
  font-weight: bold;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.pay_btn {
  border-radius: 60rpx;
  background-color: #fef1e0;
  color: #f6a22d;
  width: 220rpx;
  margin: 0;
  border: none;
}

.status-pending {
  color: #ffffff;
  background-color: #ff4d4f;
}

.status-awaiting {
  color: #ffffff;
  background-color: #faad14;
}

.status-confirmed {
  color: #ffffff;
  background-color: #1890ff;
}

.status-progress {
  color: #ffffff;
  background-color: #13c2c2;
}

.status-review {
  color: #f6a22d;
  background-color: #fffbf6;
  border: 1rpx solid #fbdaab;
}

.status-completed {
  color: #ffffff;
  background-color: #f6a22d;
}

.status-refunded {
  color: #ffffff;
  background-color: #8c8c8c;
}

.order-type {
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  position: absolute;
  font-size: 24rpx;
  z-index: 999;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.loading-tips,
.no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
}

.order-item {
  padding: 10rpx 0
}

.order-label {
  font-weight: bold;
  margin-right: 50rpx;
}

.copy-icon {
  color: #236af6;
  justify-self: self-end;
  font-weight: bold;
}
</style>
